# -*- coding: utf-8 -*-
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep


class Page(object):
    def __init__(self, driver, imgs, logs):
        self.driver = driver
        self.imgs = imgs
        self.pagelogs = logs.log_message('Selenium关键字')

    def highlight_element(self, element):
        self.driver.execute_script("element = arguments[0];" +
                                   "original_style = element.getAttribute('style');" +
                                   "element.setAttribute('style', original_style + \";" +
                                   "background: #1874cd; border: 1px solid red;\");" +
                                   "setTimeout(function(){element.setAttribute('style', original_style);}, 1000);",
                                   element)

    def notes(self, text):
        """
        页面顶部加步骤输出
        :param text:
        :return:
        """
        js1 = """var bodyDom = document.getElementsByTagName('body')[0];
                var insertDiv = document.createElement('div');
                insertDiv.id = 'sdiv';
                insertDiv.style.backgroundColor = 'red';
                insertDiv.style.height = '20px';
                insertDiv.style.color = '#FFF';
                insertDiv.style.textalign = 'center';
                insertDiv.innerText = '"""
        js2 = """';
                var firstdiv = bodyDom.getElementsByTagName('div')[0];
                bodyDom.insertBefore(insertDiv,firstdiv);
                """
        js = js1 + text + js2
        self.driver.execute_script(js)

    def show_note(self, stext):
        js = "insertDiv = document.getElementById('sdiv');insertDiv.innerText ='" + stext + "';"
        self.driver.execute_script(js)

    def find_element(self, *loc):
        try:
            WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element(*loc).is_displayed())
            element = self.driver.find_element(*loc)
            self.highlight_element(element)
            return element
        except Exception as e:
            self.pagelogs.logger.error('- [find_element]方法执行失败，原因：%s' % e)

    def find_elements(self, *loc):
        try:
            self.driver.implicitly_wait(1)
            return self.driver.find_elements(*loc)
        except Exception as e:
            self.pagelogs.logger.error('- [find_elements]方法执行失败，原因：%s' % e)

    def get_table_rows(self, *loc):
        try:
            table = self.find_element(*loc)
            rows = table.find_elements_by_tag_name('tr')
            self.pagelogs.logger.info('获取表格[%s，%s]，总行数：' % loc + '[%s]' % rows)
            return rows
        except Exception as e:
            self.pagelogs.logger.error('- [get_table_rows]方法执行失败，原因：%s' % e)

    def get_table_cols(self, *loc, row):
        try:
            table = self.find_element(*loc)
            td = table.find_elements_by_tag_name('tr')[row]
            cols = td.find_elements_by_tag_name('td')
            self.pagelogs.logger.info('获取表格[%s，%s]，第：' % loc + '[%s]行的列数为: [%s]' % (row+1, cols))
            return cols
        except Exception as e:
            self.pagelogs.logger.error('- [get_table_cols]方法执行失败，原因：%s' % e)

    def get_table_value(self, *loc, row, col):
        try:
            value = self.get_table_cols(*loc, row)[col].text
            self.pagelogs.logger.info('获取表格[%s，%s]，第：' % loc + '[%s]行[%s]列的值为: [%s]' % (row+1, col+1, value))
            return value
        except Exception as e:
            self.pagelogs.logger.error('- [get_table_value]方法执行失败，原因：%s' % e)

    def open(self, url):
        self.driver.get(url)
        self.pagelogs.logger.info('打开网页[%s]' % url)

    def make_maxwindow(self):
        self.driver.maximize_window()
        self.pagelogs.logger.info('最大化浏览器')

    def set_winsize(self, wide, hight):
        self.driver.set_window_size(wide, hight)
        self.pagelogs.logger.info('设置窗口尺寸宽[%s]高[%s]' % (wide, hight))

    def input_text(self, loc, text):
        try:
            ele = self.find_element(*loc)
            ele.click()
            ele.send_keys(text)
            self.pagelogs.logger.info('在元素[%s，%s]，输入：' % loc + '[%s]' % text)
        except TimeoutException as e:
            self.pagelogs.logger.error('- input_text()方法执行失败，原因TimeoutException:%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- 用例执行失败，原因：%s' % e)

    def clear_input_text(self, loc, text):
        try:
            ele = self.find_element(*loc)
            ele.click()
            ele.clear()
            ele.send_keys(text)
            self.pagelogs.logger.info('清空元素[%s，%s]内容，并输入' % loc + '[%s]' % text)
        except TimeoutException as e:
            self.pagelogs.logger.error('- clear_input_text()方法执行失败，原因TimeoutException：%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- 用例执行失败，原因：%s' % e)

    def element_clear(self, loc):
        try:
            ele = self.find_element(*loc)
            ele.click()
            ele.clear()
            sleep(1)
            self.pagelogs.logger.info('点击[%s，%s]的元素并清空内容' % loc)
        except TimeoutException as e:
            self.pagelogs.logger.error('- [clear]方法执行失败，原因TimeoutException：%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- 用例执行失败，原因：%s' % e)

    def left_click(self, loc):
        try:
            ele = self.find_element(*loc)
            ele.click()
            sleep(1)
            self.pagelogs.logger.info('点击[%s，%s]的元素' % loc)
        except TimeoutException as e:
            self.pagelogs.logger.error('- [left_click]方法执行失败，原因TimeoutException：%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- [left_click]执行失败，原因：%s' % e)

    def right_click(self, loc):
        try:
            ele = self.find_element(*loc)
            ActionChains(self.driver).context_click(ele).perform()
            self.pagelogs.logger.info('右键点击[%s，%s]的元素' % loc)
        except TimeoutException as e:
            self.pagelogs.logger.error('- [right_click]方法执行失败，原因TimeoutException：%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- [right_click]执行失败，原因：%s' % e)

    def move_element(self, loc):
        ele = self.find_element(*loc)
        ActionChains(self.driver).move_to_element(ele).perform()
        self.pagelogs.logger.info('鼠标移动到[%s，%s]的元素' % loc)

    def double_click(self, loc):
        ele = self.find_element(*loc)
        ActionChains(self.driver).double_click(ele).perform()
        self.pagelogs.logger.info('双击[%s，%s]的元素' % loc)

    def drag_and_drop(self, e1, e2):
        ActionChains(self.driver).drag_and_drop(e1, e2).perform()

    def click_text(self, loc):
        ele = self.find_element(loc)
        ele.click()
        self.pagelogs.logger.info("点击超链接元素：[%s，%s]" % loc)

    def close(self):
        self.driver.close()
        self.pagelogs.logger.info('关闭浏览器当前窗口')

    def browser_quit(self):
        """
        退出
        :return:
        """
        self.pagelogs.logger.info('退出浏览器\n')
        self.driver.quit()

    def submit(self, loc):
        ele = self.find_element(*loc)
        ele.submit()
        self.pagelogs.logger.info("提交表单，元素：[%s，%s]" % loc)

    def refresh(self):
        """
        刷新
        :return:
        """
        self.pagelogs.logger.info('刷新页面')
        self.driver.refresh()

    def js(self, sprit):
        """
        执行js
        :param sprit:
        :return:
        """
        sleep(2)
        self.pagelogs.logger.info('执行js：%s' % sprit)
        self.driver.execute_script(sprit)

    def get_attribute(self, loc, attribute):
        ele = self.find_element(*loc)
        return ele.get_attribute(attribute)

    def get_text(self, loc):
        try:
            ele1 = self.find_element(*loc)
            if ele1.text is None or ele1.text == '':
                sleep(3)
                ele2 = self.find_element(*loc)
                self.pagelogs.logger.info('重试，获取[%s，%s]' % loc + '元素的文本值，return:[%s]' % ele2.text)
                return ele2.text
            else:
                self.pagelogs.logger.info('获取[%s，%s]' % loc + '元素的文本值，return:[%s]' % ele1.text)
                return ele1.text
        except TimeoutException as e:
            self.pagelogs.logger.error('- [get_text]方法执行失败，原因：TimeoutException:%s' % e)
        except Exception as e:
            self.pagelogs.logger.error('- 用例执行失败，原因：%s' % e)

    def get_title(self):
        title = self.driver.title
        self.pagelogs.logger.info('获取当前页面的[title]，return：[%s]' % title)
        return title

    def add_img(self):
        self.imgs.append(self.driver.get_screenshot_as_base64())
        self.pagelogs.logger.info('获取当前窗口的截图。')

    def accpet(self):
        self.pagelogs.logger.info('接受警告框')
        self.driver.switch_to.alert.accept()

    def dismiss_alert(self):
        self.driver.switch_to.alert.dismiss()

    def switch_to_frame(self, loc):
        self.pagelogs.logger.info('切换到iframe表单')
        if1 = self.find_element(*loc)
        self.driver.switch_to.frame(if1)

    def selenium_driver(self):
        return self.driver
